import {PageContainer} from "@ant-design/pro-layout";
import ProCard from "@ant-design/pro-card";
import type {ProTableProps} from "@ant-design/pro-table";
import ProTable from "@ant-design/pro-table";
import type {GenData, GenParams} from "@/pages/system/tool/gen/type";
import columns from "@/pages/system/tool/gen/list/config/columns";
import {Button, message, Space} from "antd";
import {useRef, useState} from "react";
import type {ActionType} from "@ant-design/pro-table/lib/typing";
import {
  downloadCode,
  downloadGenExport,
  downloadGenExportTemplate, genAsync,
  genImport,
  genPageList,
  genRemove, previewCode
} from "@/services/gen/api";
import {history} from "umi";
import type {OptionActions} from "@/type/type";
import DataBaseTable from "@/pages/system/tool/gen/list/components/DataBaseTable";


export default () => {

  const actionRef = useRef<ActionType>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<(number)[]>([]);
  const [items, setItems] = useState<any []>();
  const optionAction: OptionActions<GenData> &
    {
      downloadGenCode: (ids: number[]) => void,
      getPreviewCode: (id: number) => void
    } = {
    import: {
      maxCount: 1,
      showUploadList: false,
      beforeUpload: (file) => {
        const formData = new FormData();
        formData.append('file', file);
        genImport(formData).then((res) => {
          actionRef?.current?.reload();
        });
      }
    },
    edit(id) {
      // @ts-ignore
      history.push({
        pathname: "/system/tool/gen/edit",
        query: {
          id
        }
      })
    },
    add() {
      history.push({
        pathname: "/system/tool/gen/addTable"
      })
    },
    export() {
      downloadGenExport(selectedRowKeys).then(res => {
        message.success("导出成功").then(res => {
          setSelectedRowKeys([]);
        })
      })
    },
    remove(ids: any) {
      genRemove([...ids, ...selectedRowKeys]).then(res => {
        message.success("删除成功").then(res => {
          setSelectedRowKeys([]);
          actionRef.current?.reload();
        })
      });
    },
    exportTemplate() {
      downloadGenExportTemplate().then(res => {
        message.success("下载成功").then(res => {
        })
      })
    },
    downloadGenCode(ids: number[]) {
      downloadCode(ids).then(r => message.success("下载成功"))
    },
    getPreviewCode(id: number) {
      previewCode([id]).then(res => {
        const newItems: any[] = [];
        for (let [key, value] of Object.entries(res.data)) {
          newItems.push({
            key: key,
            label: key,
            children: <div style={{height: 650, overflow: 'auto', whiteSpace: 'pre-wrap'}}>{value}</div>
          })
        }
        setItems(newItems);
      })
    },
    other: (tableNames: string[]) => {
      genAsync(tableNames).then(res => {
        message.success("同步成功").then()
      })
    }
  }


  // @ts-ignore
  const tableProps: ProTableProps<GenData, GenParams> = {
    rowSelection: {
      selectedRowKeys,
      onChange: (newSelectedRowKeys) => {
        setSelectedRowKeys(newSelectedRowKeys as number[])
      }
    },
    rowKey: "id",
    tableAlertRender: ({selectedRowKeys, selectedRows, onCleanSelected}) => {
      setSelectedRowKeys(selectedRowKeys as number[]);
      return (
        <Space size={24}>
            <span>
              已选 {selectedRowKeys.length} 项
              <a style={{marginInlineStart: 8}} onClick={onCleanSelected}>
                取消选择
              </a>
            </span>
        </Space>
      );
    },
    tableAlertOptionRender: () => {
      return (
        <Space size={16}>
          <a onClick={() => optionAction.remove}>同步</a>
          <a onClick={() => optionAction.downloadGenCode(selectedRowKeys)}>生成代码</a>
        </Space>
      );
    },
    tableStyle: {},
    size: "small",
    bordered: true,
    // @ts-ignore
    columns: columns(optionAction, items),
    request: async (params, sort, filter) => {
      return await genPageList(params).then(res => {
        return {
          data: res.data.records,
          success: true,
          total: res.data.total
        }
      })
    },
    headerTitle: (
      <Space>
        <Button type={"primary"} onClick={() => optionAction.add()}>新增</Button>
        <DataBaseTable parentActionRef={actionRef}/>
      </Space>
    ),
    actionRef
  }
  return (
    <PageContainer>
      <ProCard>
        <ProTable<GenData, GenParams> {...tableProps}>
        </ProTable>
      </ProCard>
    </PageContainer>
  )
}
